package com.tau.egonetwork.gui.core.graphs;

import java.awt.Color;
import java.awt.Paint;

import org.apache.commons.collections15.Transformer;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabItem;

import com.tau.egonetwork.algorithms.GraphAdapter;
import com.tau.egonetwork.profiles.Group;
import com.tau.egonetwork.profiles.MainProfile;
import com.tau.egonetwork.profiles.Profile;

import edu.uci.ics.jung.algorithms.layout.ISOMLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;

public class NetworkVisualizeTab<T extends Comparable<T>> extends BasicVisualizeTab<T> {

	//set colors for 15 clusters. If there's happen to be more, start recycling
	//colors - we cannot predict every scenario, but empirically this is a sound
	//large number.
	private final static Color[] clusterColors = {
		Color.RED,
		Color.GREEN,
		new Color(0, 128, 192),
		Color.ORANGE,
		Color.MAGENTA,
		Color.CYAN,
		Color.YELLOW,
		Color.WHITE,
		Color.PINK,
		Color.BLUE,
		new Color(128, 64, 0),
		new Color(128, 0, 128),
		new Color(64, 64, 128),
		new Color(116, 245, 252),
		Color.BLACK
	};
	
	public NetworkVisualizeTab(TabItem tab, Display display) {
		super(tab, display, false);
	}

	@Override
	protected Graph<T, Integer> buildGraph(MainProfile<T> profile) {
		return GraphAdapter.getGraph(profile);
	}

	@Override
	protected Layout<T, Integer> getLayout(MainProfile<T> profile, Graph<T, Integer> graph) {
		return new ISOMLayout<T, Integer>(graph);
	}

	@Override
	protected Transformer<T, Paint> getVertexFillColorTransformer(MainProfile<T> profile) {
		return new Transformer<T, Paint>() {

			@Override
			public Paint transform(T vertex) {
				
				if (currentCluster == null)
					return Color.RED;
				
				//otherwise, showing clusters, assign color:
				
				if (currentCluster.get(vertex) == null) {
					//not in any cluster, make it red with opacity:
					return new Color(Color.RED.getRed(), Color.RED.getGreen(), Color.RED.getBlue(), 100);
				}
				
				return clusterColors[(currentCluster.get(vertex) - 1) % clusterColors.length];
				
			}
		};
	}

	@Override
	protected String getGroupName(MainProfile<T> profile, T id) {
		
		String defaultGroup = "Not assigned.";

		if (profile.getGroupsList() == null)
			return defaultGroup;
		
		//go over all groups, once you find id in one of them,
		//return it (meaning, return the first that you see)!
		
		for (Group<T> g : profile.getGroupsList()) {
			for (Profile<T> p : g) {
				if (p.equals(id))
					return g.getGroupName();
			}
		}
		
		return defaultGroup;
		
	}

	@Override
	protected Float getHowMuchToScale() {
		return 1f;
	}

}
